package com.chainyoung.component_tmperson.ui.activity.cloudwallet;

import android.content.Intent;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;

import com.chainyoung.common.appcommon.entity.HdWalletCache;
import com.chainyoung.common.appcommon.hdwallet.CoinConstant;
import com.chainyoung.common.appcommon.hdwallet.OwnWalletUtils;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.view.ActionSheetDialog;
import com.chainyoung.common.view.kprogresshud.KProgressHUD;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;
import com.chainyoung.component_tmperson.di.component.DaggerPersonActivityComponent;
import com.chainyoung.component_tmperson.di.module.PersonActivityModule;
import com.chainyoung.component_tmperson.entity.CoinItem;
import com.chainyoung.component_tmperson.ui.activity.SetPinCodeActivity;
import com.chainyoung.component_tmperson.ui.activity.hdwallet.ImportHdWalletActivity;
import com.chainyoung.component_tmperson.ui.adapter.SelectCoinAdapter;
import com.chainyoung.component_tmperson.ui.mvp.contract.GetCoinContract;
import com.chainyoung.component_tmperson.ui.mvp.presenter.GetCoinListPreseneter;
import com.chainyoung.router.RouterConstants;
import com.chainyoung.router.RouterUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;

import static com.chainyoung.component_tmperson.ui.fragment.MyPurseAddrListFragment.TYPE_CLOUD;
import static com.chainyoung.component_tmperson.ui.fragment.MyPurseAddrListFragment.TYPE_LOCAl;

public class SelectCoinTypeActivity extends BaseActivity<GetCoinListPreseneter> implements GetCoinContract.View {


    @BindView(R2.id.rv_list)
    RecyclerView rvList;
    @BindView(R2.id.refresh_layout)
    SmartRefreshLayout refreshLayout;

    private SelectCoinAdapter mAdapter;
    private List<CoinItem> mData = new ArrayList<>();
    private String walletType;
    private boolean isCreatedWallet;//创建本地钱包
    private boolean isImportWallet;//导入本地钱包
    private boolean isAddWallet;//添加钱包（新创建或者导入）
    private String coinType = CoinConstant.ETH;

    private HdWalletCache hdWallet;
    private boolean isSetPinCode;


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPersonActivityComponent.builder()
                .appComponent(appComponent)
                .personActivityModule(new PersonActivityModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initUI() {
        setCurrentTitle(getString(R.string.tmperson_select_coin_type));
        walletType = getIntent().getStringExtra("walletType");
        isCreatedWallet = getIntent().getBooleanExtra("isCreatedWallet", false);
        isImportWallet = getIntent().getBooleanExtra("isImportWallet", false);
        isAddWallet = getIntent().getBooleanExtra("isAddWallet", false);
        isSetPinCode = !TextUtils.isEmpty(SPUtil.getString(LibConstant.PIN_CODE));
        initRvList();
    }

    private void initRvList() {
        rvList.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new SelectCoinAdapter(mData, !walletType.equals(TYPE_CLOUD), isCreatedWallet, isImportWallet, isAddWallet);
        rvList.setAdapter(mAdapter);
        DividerItemDecoration itemDecoration = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(ContextCompat.getDrawable(mContext, R.drawable.shape_divider_gray));
        rvList.addItemDecoration(itemDecoration);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                loadData();
            }
        });
        mAdapter.setOnSelectListener(new SelectCoinAdapter.OnSelectListener() {
            @Override
            public void onSelect(int p, String coin) {
                selectCoin(p, coin);
            }

            @Override
            public void onCreate(int p, CoinItem item) {
                gotoCreateWallet();
            }

            @Override
            public void onImport(int p, CoinItem item) {
                //导入钱包
                gotoImportWallet();
            }

            @Override
            public void onAdd(int p, CoinItem item) {
                //本地已有钱包，新创建钱包或者导入
                showCreateOrImportDialog();
            }
        });
    }


    private void gotoCreateWallet() {
        if (!isSetPinCode) {
            Intent intent = new Intent(mContext, SetPinCodeActivity.class);
            intent.putExtra("isCreateWallet", true);
            intent.putExtra("coinType", coinType);
            mContext.startActivity(intent);
            // finish();
        } else {
            //暂时只创建ETH钱包
            createWallet(SPUtil.getString(LibConstant.PIN_CODE), coinType);
        }
    }

    private void gotoImportWallet() {
        if (!isSetPinCode) {
            Intent intent = new Intent(mContext, SetPinCodeActivity.class);
            intent.putExtra("isImportWallet", true);
            intent.putExtra("coinType", coinType);
            mContext.startActivity(intent);
        } else {
            Intent intent = new Intent(mContext, ImportHdWalletActivity.class);
            intent.putExtra("coinType", coinType);
            mContext.startActivity(intent);
            finish();
        }
    }

    private void showCreateOrImportDialog(){
        new ActionSheetDialog(mContext).builder().setCancelable(true).setCanceledOnTouchOutside(true).
                addSheetItem("创建钱包", ActionSheetDialog.SheetItemColor.Blue, onSheetItemClickListener).
                addSheetItem("导入钱包", ActionSheetDialog.SheetItemColor.Blue, onSheetItemClickListener).
                show();
    }

    ActionSheetDialog.OnSheetItemClickListener onSheetItemClickListener = new ActionSheetDialog.OnSheetItemClickListener() {
        @Override
        public void onClick(int which) {
           switch (which){
               case 1:
                   gotoCreateWallet();
                   break;
               case 2:
                   gotoImportWallet();
                   break;
           }
        }
    };



    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        isSetPinCode = !TextUtils.isEmpty(SPUtil.getString(LibConstant.PIN_CODE));
        loadData();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmperson_select_cointype;
    }


    /**
     * 创建 钱包
     */
    private void createWallet(String password, String coinType) {
        hdWallet = OwnWalletUtils.createNewAccount(password, coinType);
        mPresenter.getAllHdWalletCaches(hdWallet.getCoinType());
    }


//----------------------------------------------------------------网络请求---------------------------------------------------

    private void loadData() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        map.put("wallet_type", walletType);
        mPresenter.getCoinList(map);
    }

    private void selectCoin(int p, String coin) {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        map.put("coin", coin);
        mPresenter.selectCoin(map);

    }

    @Override
    public void onGetCoinListSuccess(List<CoinItem> data) {
        refreshLayout.finishRefresh();
        if (data == null) {
            return;
        }

        mData.clear();
        if (walletType.equals(TYPE_LOCAl)) {
            for (CoinItem coinItem : data) {
                if (coinItem.getCoin().toLowerCase().equals("eth")) {
                    mData.add(coinItem);
                }
            }
        } else {
            mData.addAll(data);
        }

        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onGetCoinListFailed() {
        refreshLayout.finishRefresh();
    }

    @Override
    public void onSelectCoinSuccess(String data) {

    }

    //-------------------------------------------本地钱包数据库--------------------------------------------------------------------------------

    @Override
    public void onAddHdWalletCacheSuccess(HdWalletCache data) {

        KProgressHUD.create(mContext)
                .setCustomView(mContext, R.drawable.tips_correct)
                .setLabel(getString(R.string.tmperson_wallet_created))
                .show().setDuration(1500);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RouterUtils.getInstance()
                        .build(RouterConstants.PATH_MAIN_MARKET_ACTIVITY)
                        .withInt("page", 3)
                        .withBoolean("isGetWallet", true)
                        .navigation(mContext);
                finish();
            }
        }, 1500);

    }

    @Override
    public void onGetAllHdWalletCaches(List<HdWalletCache> datas) {
        // 给新增钱包取名
        int num = datas == null ? 1 : datas.size() + 1;
        hdWallet.setWalletName(hdWallet.getCoinType() + "-" + num);
        mPresenter.addHdWalletCache(hdWallet);
    }


}
